<template>
  <div class="me-page">
    <div class="user-card">
      <i-card
        :title="userInfo.nickName"
        :thumb="userInfo.avatarUrl"
        :extra="gender"
      >
        <view slot="content">{{ userInfo.country }} {{ userInfo.province }}</view>
        <view slot="footer">{{ userInfo.city }}</view>
      </i-card>
    </div>
    <!-- 展示进度条 -->
    <ProgressBar />
    <i-button
      v-if="isAuthority"
      type="primary"
      @click="scanBooks"
    >扫码添加图书</i-button>
    <div v-else>
      <i-button
        v-if="canIUse"
        type="primary"
        open-type="getUserInfo"
        @getuserinfo="bindGetUserInfo"
      >点击授权</i-button>
      <i-button v-else>请升级微信版本</i-button>
    </div>
    <i-message id="message" />
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from 'vuex';
import ProgressBar from '@/components/ProgressBar';
import requestData from '@/utils/request';
import { $Message } from '../../../static/iview-weapp/base/index';
export default {
  data () {
    return {
      canIUse: wx.canIUse('button.open-type.getUserInfo'),
      userInfo: {
        avatarUrl: '/static/images/default-user.png',
        gender: 0,
        nickName: '未知',
        country: '未知',
        city: '点击授权，获取更多功能'
      },
      isAuthority: false, // 是否授权
    }
  },
  components: {
    ProgressBar,
  },
  onShow () {
    // 查看是否授权
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: (res) => {
              wx.setStorageSync('isLogin',true); // 存储登录状态
              this.isAuthority = true;
              this.userInfo = res.userInfo;
            },
            fail: (err) => {
              console.log('error', err);
            }
          })
        }
      },
      fail: (err) => {
        console.log('error', err);
      }
    })
  },
  methods: {
    ...mapActions('meModule', ['addUser']),
    ...mapActions('bookModule', ['getBookInfo']),
     async bindGetUserInfo (e) {
      const { userInfo = {}, errMsg } = e.mp.detail;
      if (errMsg === 'getUserInfo:fail auth deny') { // 点击‘拒绝’
        return false;
      }
      // 点击‘允许’
      wx.setStorageSync('isLogin',true); // 存储登录状态
      this.isAuthority = true;
      this.userInfo = userInfo;
      // 添加用户,写进数据库
      this.addUser({
        openId: this.openId,
        nickName: userInfo.nickName,
        avatarUrl: userInfo.avatarUrl,
      })
    },
    scanBooks () {
      // 允许从相机和相册扫码
      wx.scanCode({
        scanType: ['barCode', 'qrCode', 'datamatrix', 'pdf417	'],
        success: async (res) => {
          const isbnCode = res.result;
          if (isbnCode) {
            await this.getBookInfo({
              isbnCode,
              openId: this.openId
            });
            const successMsg = this.saveBookInfoRes[0];
            const errMsg = this.saveBookInfoRes[1];
            if (errMsg) {
              $Message({
                content: errMsg,
                type: 'warning',
              })
            } else {
              $Message({
                content: successMsg,
              });
            }
          }
        },
        fail: (err) => {
          console.log('error', err);
        }
      })
    }
  },
  computed: {
    ...mapState('meModule', {
      openId (state) {
        return state.openId;
      },
    }),
    ...mapState('bookModule', {
      saveBookInfoRes (state) {
        return state.saveBookInfoRes;
      },
    }),
    gender () {
      //性别 0：未知、1：男、2：女
      const { gender } = this.userInfo;
      switch (gender) {
        case 0:
          return '未知';
        case 1:
          return '男';
        default:
          return '女';
      }
    }
  },
}
</script>

<style scoped lang="less">
  .me-page {
   .user-card {
      margin-top: 20rpx;
    }
  }
</style>
